package passenger

import (
	v1 "gitee.com/sweetsunnyflower/carpooling-server-go/app/http/controllers/api/v1"
	"gitee.com/sweetsunnyflower/carpooling-server-go/app/models/passenger"
	"gitee.com/sweetsunnyflower/carpooling-server-go/app/policies"
	"gitee.com/sweetsunnyflower/carpooling-server-go/app/requests"
	"github.com/gofiber/fiber/v2"
	"github.com/spf13/cast"
)

type PassengersController struct {
	v1.BaseController
}

func (controller *PassengersController) Index(c *fiber.Ctx) error {
	passengers := passenger.All()
	return controller.Json(c, passengers)
}

func (controller *PassengersController) Show(c *fiber.Ctx) error {
	passengerModel := passenger.Get(cast.ToUint64(c.Query("id")))
	if passengerModel.ID == 0 {
		return controller.NotFound(c)
	}
	return controller.Json(c, passengerModel)
}

func (controller *PassengersController) Store(c *fiber.Ctx) error {

	// request := new(requests.PassengerRequest)

	// if errors := requests.ValidatePassenger(c, request); len(errors) > 0 {
	// 	return controller.ValidationError(c, errors)
	// }

	if passenger.GetByUserId(controller.Auth(c)).ID > 0 {
		return controller.Faield(c, "乘客信息已经存在，无需再次添加")
	}

	passengerModel := passenger.Passenger{
		// FieldName:      request.FieldName,
		UserId: controller.Auth(c),
	}
	passengerModel.Create()
	if passengerModel.ID > 0 {
		return controller.Json(c, passengerModel)
	} else {
		return controller.Faield(c, "创建失败")
	}
}

func (controller *PassengersController) Update(c *fiber.Ctx) error {

	passengerModel := passenger.Get(cast.ToUint64(c.Query("id")))
	if passengerModel.ID == 0 {
		return controller.NotFound(c)
	}

	userId := controller.Auth(c)
	if ok := policies.CanModifyPassenger(userId, passengerModel); !ok {
		return controller.Forbidden(c)
	}

	request := new(requests.PassengerRequest)

	if errors := requests.ValidatePassenger(c, request); len(errors) > 0 {
		return controller.ValidationError(c, errors)
	}

	// passengerModel.FieldName = request.FieldName
	rowsAffected := passengerModel.Save()
	if rowsAffected > 0 {
		return controller.Success(c)
	} else {
		return controller.Faield(c, "更新失败")
	}
}

func (controller *PassengersController) Delete(c *fiber.Ctx) error {

	passengerModel := passenger.Get(cast.ToUint64(c.Query("id")))
	if passengerModel.ID == 0 {
		return controller.NotFound(c)
	}

	userId := controller.Auth(c)

	if ok := policies.CanModifyPassenger(userId, passengerModel); !ok {
		return controller.Forbidden(c)
	}

	rowsAffected := passengerModel.Delete()
	if rowsAffected > 0 {
		return controller.Success(c)
	}

	return controller.Faield(c, "删除失败")
}
